/// [Pandigital products](https://projecteuler.net/problem=32)
use std::collections::HashMap;

fn main() {
    let mut pandigitals = HashMap::new();
    let mut a = 1;
    loop {
        let mut b = a;
        loop {
            let c = a * b;
            match is_pandigital(c, a, b) {
                (true, 9) => {
                    println!("{:5} = {:5} x {:5}", c, a, b);
                    pandigitals.insert(c, c);
                    b += 1;
                }
                (_, 8) | (_, 9) => {
                    b += 1;
                }
                (_, 7) => {
                    b *= 3;
                }
                (_, n) if n < 7 => {
                    b = b * 10 + 1;
                }
                _ => break,
            }
        }
        a += 1;
        let (_, n) = is_pandigital(a * a, a, a);
        if n > 9 {
            break;
        }
    }
    println!("The len of all products: {}", pandigitals.len());
    println!("The sum of all products: {}", pandigitals.values().sum::<usize>());
}

fn is_pandigital(product: usize, multiplier: usize, multiplicand: usize) -> (bool, usize) {
    let mut nums = (product.to_string() + &multiplier.to_string() + &multiplicand.to_string())
        .chars()
        .map(|x| x.to_string().parse::<usize>().unwrap_or_default())
        .collect::<Vec<_>>();
    nums.sort();
    for (i, &j) in nums.iter().enumerate() {
        if j - i != 1 {
            return (false, nums.len());
        }
    }
    (true, nums.len())
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn is_work() {
        assert_eq!(is_pandigital(7254, 39, 186), (true, 9))
    }
}
